package com.xiu.travel.socket;

import com.xiu.travel.util.SecurityUtils;
import com.xiu.travel.util.api.CommonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 * socket消息控制器
 * </p>
 *
 * @author qianl
 * @since 2023-2-6
 */
@RestController
@Tag(name = "socket消息接口")
@RequestMapping("/portal/open/send")
@CrossOrigin
public class WSController {
    @Autowired
    private SocketServer socketServer;

    @PostMapping("SendIds")
    @Operation(summary = "发送消息到id")
    public CommonResult<WSBody[]> send(@RequestBody WSSendMsg msg) throws IOException {
        WSBody[] sendData = null;
        if (msg.id().length == 0) {
            sendData = SocketServer.getWebSocketSet().stream().map(ws -> new WSBody(ws.id, ws.client)).toArray(WSBody[]::new);
            SocketServer.sendMessage(msg.msg(), new HashSet<>());
        } else {
            sendData = SocketServer.getWebSocketSet().stream().filter(item -> Arrays.asList(msg.id()).contains(item.id)).map(ws -> new WSBody(ws.id, ws.client)).toArray(WSBody[]::new);
            SocketServer.sendMessage(msg.msg(), new HashSet<>(List.of(sendData)));
        }
        return CommonResult.success(sendData);
    }

    @PostMapping("SendIdAndClient")
    @Operation(summary = "发送消息到指定的id和客户端")
    public CommonResult<Boolean> sendIdAndClient(@RequestBody WSSingleSendMsg msg) throws IOException {
        SocketServer.sendMessage(msg.msg(), new HashSet<>(Collections.singleton(new WSBody(msg.id(), msg.client()))));
        return CommonResult.success(SocketServer.getWebSocketSet().stream().filter(item -> item.id.equals(msg.id()) && item.client.equals(msg.client())).toArray().length > 0);
    }

    @PostMapping("GetAllOnline")
    @Operation(summary = "获取所有在线信息")
    public CommonResult<WSBody[]> getOnlineById() {
        return CommonResult.success(SocketServer.getWebSocketSet().stream().map(ws -> new WSBody(ws.id, ws.client)).toArray(WSBody[]::new));
    }

    @PostMapping("GetOnline")
    @Operation(summary = "获取我的在线信息")
    public CommonResult<WSBody[]> getOnline() throws IOException {
        return CommonResult.success(SocketServer.getWebSocketSet().stream().filter(item -> Objects.equals(item.id, SecurityUtils.getUserId().toString())).map(ws -> new WSBody(ws.id, ws.client)).toArray(WSBody[]::new));
    }

}
